package com.luoguijia.disk.files.service.impl;

import com.luoguijia.disk.files.entity.FileEntity;
import com.luoguijia.disk.files.entity.SearchFileEntity;
import com.luoguijia.disk.files.repository.FileDao;
import com.luoguijia.disk.files.service.FileIoService;
import com.luoguijia.disk.files.service.FileService;
import com.luoguijia.disk.mybatis.entity.PtFileEntity;
import com.luoguijia.disk.mybatis.entity.PtUserEntity;
import com.luoguijia.disk.mybatis.entity.PtShareEntity;
import com.luoguijia.disk.share.service.ShareService;
import java.util.Date;
import java.util.UUID;
import com.luoguijia.disk.mybatis.flexigrid.PagingEntity;
import com.luoguijia.disk.mybatis.flexigrid.TblResponseEntity;
import com.luoguijia.disk.user.entity.SearchUserEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

import javax.annotation.Resource;
import java.util.List;

@Service
public class FileServiceImpl implements FileService {

    @Resource
    private FileDao fileDao;

    @Resource
    private ShareService shareService;

    public List<PtFileEntity> getFileList(){
        return fileDao.queryFileList();
    }

    @Override
    public void saveFileInfo(List<PtFileEntity> ptFileEntityList) {
        fileDao.deleteFileAll();
        fileDao.saveFileInfo(ptFileEntityList);
    }

    @Override
    public boolean logicDeleteFile(String fileId) {
        // 1. 查询文件信息
        PtFileEntity file = fileDao.getFileById(fileId);
        if (file == null) {
            return false;
        }

        // 2. 创建FileEntity对象设置删除信息
        FileEntity deleteFile = new FileEntity();
        deleteFile.setId(fileId);
        deleteFile.setIsDeleted(1); // 1表示已删除(放入回收站)
        deleteFile.setRecycleTime(new Date());

        // 3. 执行逻辑删除
        return fileDao.logicDelete(deleteFile) > 0;
    }    // 上传文件存储的基础路径，可根据实际情况修改，比如放到项目外的绝对路径

    private static final String UPLOAD_BASE_PATH = "D:\\vcs\\group2_code\\doc\\upload";

    @Override
    public String uploadFile(MultipartFile file) {
        if (file.isEmpty()) {
            throw new RuntimeException("上传文件为空");
        }
        // 生成唯一文件名，避免重复
        String originalFileName = file.getOriginalFilename();
        String fileName = UUID.randomUUID().toString() +
                originalFileName.substring(originalFileName.lastIndexOf("."));
        File dest = new File(UPLOAD_BASE_PATH + fileName);
        // 确保目录存在
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            file.transferTo(dest);
            // 返回文件存储的相对路径，可根据需求调整返回内容，比如完整访问 URL 等
            return UPLOAD_BASE_PATH + fileName;
        } catch (IOException e) {
            throw new RuntimeException("文件上传失败", e);
        }
    }

    // 在线媒体浏览
    @Override
    public PtFileEntity getFileById(String fileId) {
        return fileDao.getFileById(fileId);
    }



    @Override
    public TblResponseEntity<PtFileEntity> queryFileInfoListByPage(SearchFileEntity entity, PagingEntity paging) {

        TblResponseEntity<PtFileEntity> tblResponseEntity = new TblResponseEntity<>();
        Integer total = fileDao.queryFileTotal(entity);
        tblResponseEntity.setTotal(total);
        //计算当前页数
        paging.deal(PtFileEntity.class,total);
        tblResponseEntity.setPage(paging.getPage());

        List<PtFileEntity> list = fileDao.queryFileInfoListByPage(entity,paging);
        tblResponseEntity.setRawRecords(list);

        tblResponseEntity.deal();

        return tblResponseEntity;
    }

/*    @Override
    public PtFileEntity queryFileInfoById(String fileUuid) {
        return fileDao.queryFileInfoById(fileUuid);
    }*/

    @Override
    public List<PtFileEntity> queryFileListAll() {
        return fileDao.queryFileListAll();
    }

    @Override
    public void deleteFileByIds(String ids) {
        String fileArray[] = ids.split(",");
        fileDao.deleteFileByIds(fileArray);

    }


    @Override
    public String generateShareLink(String fileId) {
        // 1. 根据fileId查询文件信息
        PtFileEntity file = fileDao.getFileById(fileId);
        if (file == null) {
            throw new RuntimeException("文件不存在");
        }

        // 2. 生成唯一的分享码
        String shareCode = UUID.randomUUID().toString().replace("-", "");

        // 3. 创建PtShareEntity对象并保存到数据库
        PtShareEntity shareEntity = new PtShareEntity();
        // 使用getFileUuid()代替getFileId()
        shareEntity.setFileId(Long.parseLong(file.getFileUuid()));
        shareEntity.setCreatorId(getCurrentUserId()); // 需要实现获取当前用户ID的方法
        shareEntity.setCreateTime(new Date());
        // 设置过期时间为7天
        Date expireTime = new Date(System.currentTimeMillis() + 7 * 24 * 60 * 60 * 1000);
        shareEntity.setExpireTime(expireTime);
        shareEntity.setShareCode(shareCode);
        shareEntity.setStatus(1); // 1表示有效

        shareService.addShareInfoById(shareEntity);

        // 4. 构建分享链接
        // 假设应用部署在localhost:8080
        String baseUrl = "http://localhost:8080";
        String shareLink = baseUrl + "/share/access?code=" + shareCode;

        return shareLink;
    }

    @Override
    public TblResponseEntity<PtFileEntity> queryRecycleFileListByPage(SearchFileEntity entity, PagingEntity paging) {
        TblResponseEntity<PtFileEntity> tblResponseEntity = new TblResponseEntity<>();
        Integer total = fileDao.queryRecycleFileTotal(entity);
        tblResponseEntity.setTotal(total);
        //计算当前页数
        paging.deal(PtFileEntity.class, total);
        tblResponseEntity.setPage(paging.getPage());

        List<PtFileEntity> list = fileDao.queryRecycleFileInfoListByPage(entity, paging);
        tblResponseEntity.setRawRecords(list);

        tblResponseEntity.deal();

        return tblResponseEntity;
    }

    @Override
    public boolean restoreFileFromRecycle(String fileId) {
        // 实现从回收站恢复文件的逻辑
        // 1. 查询文件信息
        PtFileEntity file = fileDao.getFileById(fileId);
        if (file == null) {
            return false;
        }

        // 2. 恢复文件（更新文件状态）
        // 假设数据库中有一个isDeleted字段表示是否在回收站中
        // file.setIsDeleted(false);
        // fileDao.updateFile(file);

        // 这里只是示例实现，实际逻辑需要根据数据库结构调整
        return fileDao.restoreFileFromRecycle(fileId) > 0;
    }

    @Override
    public boolean permanentlyDeleteFile(String fileId) {
        // 实现永久删除文件的逻辑
        // 1. 查询文件信息
        PtFileEntity file = fileDao.getFileById(fileId);
        if (file == null) {
            return false;
        }

        // 2. 如果是物理文件，删除实际文件
        if (file.getFileType() == FileIoService.FILE_TYPE_FILE) {
            // 这里需要实现从存储系统（如OBS）删除文件的逻辑
            // 例如: fileIoService.deleteFile(file.getFilePath());
        }

        // 3. 从数据库中删除记录
        return fileDao.deleteFile(fileId) > 0;
    }

    @Override
    public boolean batchRestoreFromRecycle(String[] fileIds) {
        // 实现批量恢复文件的逻辑
        int successCount = 0;
        for (String fileId : fileIds) {
            if (restoreFileFromRecycle(fileId)) {
                successCount++;
            }
        }
        return successCount == fileIds.length;
    }

    @Override
    public boolean batchPermanentlyDelete(String[] fileIds) {
        // 实现批量永久删除文件的逻辑
        int successCount = 0;
        for (String fileId : fileIds) {
            if (permanentlyDeleteFile(fileId)) {
                successCount++;
            }
        }
        return successCount == fileIds.length;
    }

    // 获取当前用户ID的方法（需要根据实际情况实现）
    private Long getCurrentUserId() {
        // 这里只是示例，实际应用中需要从登录信息中获取
        return 1L;
    }





    //      文件查询
    @Override
    public PtFileEntity queryFileInfoById(String fileUuid) {
        return fileDao.queryFileInfoById(fileUuid);
    }
    //文件修改
    @Override
    public void modifyFileInfoById(PtFileEntity entity) {
        fileDao.modifyFileInfoById(entity);
    }
}
